﻿using System;

// 定义事件发布者
public class Publisher
{
    // 定义事件
    public event EventHandler<string> MessagePublished;

    // 发布消息的方法
    public void PublishMessage(string message)
    {
        OnMessagePublished(message);
    }

    // 触发事件的方法
    protected virtual void OnMessagePublished(string message)
    {
        MessagePublished?.Invoke(this, message);
    }
}

// 定义事件订阅者
public class Subscriber
{
    // 订阅事件
    public void Subscribe(Publisher publisher)
    {
        publisher.MessagePublished += HandleMessage;
    }

    // 取消订阅事件
    public void Unsubscribe(Publisher publisher)
    {
        publisher.MessagePublished -= HandleMessage;
    }

    // 处理事件的方法
    private void HandleMessage(object sender, string message)
    {
        Console.WriteLine("Received message: " + message);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Publisher publisher = new Publisher();
        Subscriber subscriber1 = new Subscriber();
        Subscriber subscriber2 = new Subscriber();

        // 订阅事件
        subscriber1.Subscribe(publisher);
        subscriber2.Subscribe(publisher);

        // 发布消息
        publisher.PublishMessage("Hello, subscribers!");

        // 取消订阅事件
        subscriber1.Unsubscribe(publisher);

        // 再次发布消息
        publisher.PublishMessage("Are you still there?");

        Console.ReadLine();
    }
}